import React, { Component } from "react";
import { connect } from "react-redux";
import { List ,Badge} from "antd-mobile";

@connect(state => state)
class Msg extends Component {
  getLast(arr) {
    return arr[arr.length - 1];
  }

  render() {
    if (!this.props.chatuser.chatmsg.length) {
      return null;
    }
    const Item = List.Item;
    const Brief = Item.Brief;
    const userid = this.props.user._id;
    const userinfo = this.props.chatuser.users;
    const msgGroup = {};
    this.props.chatuser.chatmsg.map(v => {
      msgGroup[v.chatid] = msgGroup[v.chatid] || [];
      msgGroup[v.chatid].push(v);
    });
    const chatList = Object.values(msgGroup).sort((a,b)=>{
      const a_last = this.getLast(a).create_time
      const b_last = this.getLast(b).create_time
      console.log(b_last,a_last)
      return b_last - a_last
    })
    console.log(chatList)
    return (
      <div>
        {chatList.map(v => {
          const lastItem = this.getLast(v);
          const targetId = v[0].from === userid ? v[0].to : v[0].from;
          const name = userinfo[targetId] ? userinfo[targetId].name : "用户名";
          const avatar = userinfo[targetId] ? userinfo[targetId].avatar : "";

          const unread = v.filter(v=>!v.read&&v.to === userid).length

          return (
            <List key={lastItem._id}>
              <Item 
              extra={<Badge text={unread}></Badge>}
              thumb={require(`../img/${avatar}.png`)}
              arrow="horizontal"
              onClick={()=>{
                this.props.history.push(`/chat/${targetId}`)
              }}
              >
                {lastItem.content}
                <Brief>{name}</Brief>
              </Item>
            </List>
          );
        })}
      </div>
    );
  }
}

export default Msg;
